import axios from 'axios';
import { message } from 'antd';


// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL || '',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 令牌管理类
class TokenManager {
  constructor() {
    this.isRefreshing = false;
    this.refreshPromise = null;
    this.failedQueue = [];
  }

  getAccessToken() {
    return localStorage.getItem('access_token');
  }

  getRefreshToken() {
    return localStorage.getItem('refresh_token');
  }

  setTokens(accessToken, refreshToken) {
    localStorage.setItem('access_token', accessToken);
    localStorage.setItem('refresh_token', refreshToken);
  }

  clearTokens() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
  }

  async refreshTokens() {
    if (this.isRefreshing) {
      return this.refreshPromise;
    }

    const refreshToken = this.getRefreshToken();
    if (!refreshToken) {
      throw new Error('No refresh token available');
    }

    this.isRefreshing = true;
    this.refreshPromise = this.performRefresh(refreshToken);

    try {
      const result = await this.refreshPromise;
      this.processQueue(null, result.access_token);
      return result;
    } catch (error) {
      this.processQueue(error, null);
      this.clearTokens();
      throw error;
    } finally {
      this.isRefreshing = false;
      this.refreshPromise = null;
    }
  }

  async performRefresh(refreshToken) {
    try {
      const apiUrl = process.env.REACT_APP_API_URL || '';
      const response = await axios.post(
        `${apiUrl}/api/v1/auth/refresh`,
        { refresh_token: refreshToken },
        {
          headers: { 'Content-Type': 'application/json' }
        }
      );

      const { access_token, refresh_token } = response.data;
      this.setTokens(access_token, refresh_token);
      
      return { access_token, refresh_token };
    } catch (error) {
      console.error('令牌刷新失败:', error);
      throw error;
    }
  }

  processQueue(error, token = null) {
    this.failedQueue.forEach(({ resolve, reject }) => {
      if (error) {
        reject(error);
      } else {
        resolve(token);
      }
    });
    
    this.failedQueue = [];
  }

  addToQueue(resolve, reject) {
    this.failedQueue.push({ resolve, reject });
  }
}

const tokenManager = new TokenManager();

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('=== 发送请求详情 ===');
    console.log('请求URL:', config.baseURL + config.url);
    console.log('请求方法:', config.method);
    console.log('请求头:', config.headers);
    console.log('请求参数:', config.params);
    console.log('请求数据:', config.data);
    console.log('环境变量 REACT_APP_API_URL:', process.env.REACT_APP_API_URL);
    console.log('===================');
    
    const token = tokenManager.getAccessToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('=== 收到响应详情 ===');
    console.log('响应状态:', response.status);
    console.log('响应头:', response.headers);
    console.log('响应数据:', response.data);
    console.log('===================');
    // 检查是否需要刷新令牌
    if (response.headers['x-token-refresh-required'] === 'true') {
      const remainingSeconds = parseInt(response.headers['x-token-remaining-seconds'] || '0');
      console.log(`令牌将在 ${remainingSeconds} 秒后过期，准备刷新`);
      
      // 异步刷新令牌，不阻塞当前请求
      tokenManager.refreshTokens().catch(error => {
        console.error('自动刷新令牌失败:', error);
      });
    }

    return response.data;
  },
  async (error) => {
    console.error('=== 响应错误详情 ===');
    console.error('错误对象:', error);
    console.error('错误消息:', error.message);
    console.error('错误代码:', error.code);
    console.error('请求配置:', error.config);
    console.error('响应数据:', error.response?.data);
    console.error('响应状态:', error.response?.status);
    console.error('===================');

    const originalRequest = error.config;
    const status = error.response?.status;
    const requestUrl = error.config?.url;
    // 处理401未授权错误
    if (status === 401 && !originalRequest._retry) {
      // 如果是登录接口的401错误，不要重试
      if (requestUrl && requestUrl.includes('/login')) {
        return Promise.reject(error);
      }

      // 如果是刷新令牌接口的401错误，直接清除令牌并跳转登录
      if (requestUrl && requestUrl.includes('/refresh')) {
        tokenManager.clearTokens();
        window.location.href = '/login';
        message.error('登录已过期，请重新登录');
        return Promise.reject(error);
      }

      originalRequest._retry = true;

      if (tokenManager.isRefreshing) {
        // 如果正在刷新，将请求加入队列
        return new Promise((resolve, reject) => {
          tokenManager.addToQueue(
            (token) => {
              originalRequest.headers.Authorization = `Bearer ${token}`;
              resolve(api(originalRequest));
            },
            (err) => {
              reject(err);
            }
          );
        });
      }

      try {
        const result = await tokenManager.refreshTokens();
        originalRequest.headers.Authorization = `Bearer ${result.access_token}`;
        return api(originalRequest);
      } catch (refreshError) {
        console.error('令牌刷新失败，跳转到登录页:', refreshError);
        window.location.href = '/login';
        message.error('登录已过期，请重新登录');
        return Promise.reject(refreshError);
      }
    }

    // 处理其他错误
    let errorMsg = '操作失败，请重试';
    if (error.response?.data) {
      if (Array.isArray(error.response.data.detail)) {
        errorMsg = error.response.data.detail.map(item => item.msg).join('; ');
      } else if (typeof error.response.data.detail === 'string') {
        errorMsg = error.response.data.detail;
      } else {
        errorMsg = JSON.stringify(error.response.data);
      }
    }

    if (status === 403) {
      message.error('没有权限执行此操作');
    } else if (status === 500) {
      message.error('服务器内部错误，请稍后再试');
    } else {
      // 对于登录接口，不在这里显示错误消息，让AuthContext处理
      if (!(requestUrl && requestUrl.includes('/login'))) {
        message.error(errorMsg);
      }
    }

    return Promise.reject(error);
  }
);

// 身份验证相关API
export const authAPI = {
  login: (username, password) => {
    const data = new URLSearchParams();
    data.append('username', username);
    data.append('password', password);
    return api.post('/api/v1/auth/login', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
  },
  getCurrentUser: () => api.get('/api/v1/auth/me'),
  
  // 修复logout方法，支持传递refresh_token
  logout: (refreshToken = null) => {
    const data = refreshToken ? { refresh_token: refreshToken } : {};
    return api.post('/api/v1/auth/logout', data);
  },
  
  // 添加refreshToken方法
  refreshToken: (refreshToken) => {
    return api.post('/api/v1/auth/refresh', { refresh_token: refreshToken });
  },
  
  // 添加获取令牌信息的方法
  getTokenInfo: () => api.get('/api/v1/auth/token-info'),
  
  // 添加全设备登出方法
  logoutAll: () => api.post('/api/v1/auth/logout-all')
};

// 导出TokenManager实例供外部使用
export { tokenManager };

// 数据查询相关API
export const dataAPI = {
  // 数据相关API
  // 搜索海关数据（支持模糊查询）
  searchData: (params) => api.get('/api/v1/data/search', { params }),
  
  // 获取进口商建议
  getImportersSuggestions: (query, limit = 10) => 
    api.get('/api/v1/data/importers/suggestions', { params: { query, limit } }),
  
  // 获取出口商建议
  getExportersSuggestions: (query, limit = 10) => 
    api.get('/api/v1/data/exporters/suggestions', { params: { query, limit } }),

  // HSCode相关API - 简化版本
  // 批量获取多个HSCode的中文描述
  getMultipleHSCodeDescriptions: (hscodes) => 
    api.post('/api/v1/data/hscode/batch', hscodes),
  
  // 保持原有的search方法以兼容现有代码
  search: (params) => api.get('/api/v1/data/search', { params }).then(response => response.data),
  export: (queryParams) => api.post('/api/v1/data/export', { query_params: queryParams }),
  getCustomsCodes: () => api.get('/api/v1/data/customs-codes'),
  getCountries: () => api.get('/api/v1/data/countries'),
  aiSearch: (searchValue, exportCountries, importCountries) => api.post('/api/v1/ai/search', {
    search_value: searchValue,
    export_countries: exportCountries,
    import_countries: importCountries
  }),
  // 数据管理相关API
  create: (data) => api.post('/api/v1/data', data),
  update: (id, data) => api.put(`/api/v1/data/${id}`, data),
  delete: (id) => api.delete(`/api/v1/data/${id}`),
  bulkDelete: (ids) => api.post('/api/v1/data/bulk-delete', { data_ids: ids }),
  bulkDeleteByCondition: (queryParams) => api.post('/api/v1/data/bulk-delete-by-condition', { query_params: queryParams })
};

// // 用户管理相关API
// export const importAPI = {
//   importExcel: async (file) => {
//     const formData = new FormData();
//     formData.append('file', file);
//     return axios.post('/api/v1/import/', formData, {
//       headers: {
//         'Content-Type': 'multipart/form-data'
//       }
//     });
//   }
// };

// 用户管理相关API
export const userAPI = {
  getUsers: () => api.get('/api/v1/user/'),
  createUser: (userData) => api.post('/api/v1/user/', userData),
  updateUser: (username, userData) => api.put(`/api/v1/user/${username}`, userData),
  deleteUser: (username) => api.delete(`/api/v1/user/${username}`),
  getUserByUsername: (username) => api.get(`/api/v1/user/${username}`),
  getUsersByGroup: (groupId) => api.get(`/api/v1/user/group/${groupId}`)
};

// 角色管理相关API
export const roleAPI = {
  createRole: (roleData) => api.post('/api/v1/role/', roleData),
  updateRole: (roleId, roleData) => api.put(`/api/v1/role/${roleId}`, roleData),
  deleteRole: (roleId) => api.delete(`/api/v1/role/${roleId}`),
  getRoles: () => api.get('/api/v1/role/'),
  getRole: (roleId) => api.get(`/api/v1/role/${roleId}`),
  getAvailablePermissions: () => api.get('/api/v1/role/permissions/available')
};

// 用户组管理相关API
export const groupAPI = {
  createGroup: (groupData) => api.post('/api/v1/group/', groupData),
  updateGroup: (groupId, groupData) => api.put(`/api/v1/group/${groupId}`, groupData),
  deleteGroup: (groupId) => api.delete(`/api/v1/group/${groupId}`),
  getGroups: () => api.get('/api/v1/group/'),
  getGroup: (groupId) => api.get(`/api/v1/group/${groupId}`),
  addUserToGroup: (groupId, username) => api.post(`/api/v1/group/${groupId}/users/${username}`),
  removeUserFromGroup: (groupId, username) => api.delete(`/api/v1/group/${groupId}/users/${username}`)
};

// 配置管理相关API
export const configAPI = {
  // 获取系统配置
  getSystemConfigs: (category) => {
    const params = category ? { category } : {};
    return api.get('api/v1/config/system', { params });
  },
  
  // 获取配置类型元数据
  getConfigTypes: () => api.get('api/v1/config/types'),
  
  // 更新系统配置
  updateSystemConfig: (configKey, data) => api.put(`api/v1/config/system/${configKey}`, data),
  
  // 获取所有角色配置
  getAllRoleConfigs: () => api.get('api/v1/config/role-overrides/all'),
  
  // 获取角色配置
  getRoleConfigs: (roleId) => api.get(`api/v1/config/role-overrides/${roleId}`),
  
  // 创建角色配置
  createRoleConfig: (data) => api.put(`api/v1/config/role-overrides/${data.role_id}/${data.config_key}`, {
    config_value: data.config_value
  }),
  
  // 删除角色配置
  deleteRoleConfig: (roleId, configKey) => api.delete(`api/v1/config/role-overrides/${roleId}/${configKey}`),
  
  // 获取用户有效配置
  getEffectiveConfigs: () => api.get('api/v1/config/effective'),
  
  // 获取国家映射
  getCountryMapping: () => api.get('api/v1/config/country-mapping'),
  
  // 添加国家映射
  addCountryMapping: (data) => api.post('api/v1/config/country-mapping', data),
  
  // 更新整个国家映射配置
  updateCountryMapping: (countryMapping) => api.put('api/v1/config/country-mapping', {
    country_mapping: countryMapping
  })
};

// 数据导入相关API
export const importAPI = {
  importExcel: (file) => {
    const formData = new FormData();
    formData.append('file', file);
    return api.post('/api/v1/import/excel', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
};


// 增强导入API
export const enhancedImportAPI = {
  // 批量上传文件
  uploadFiles: (formData) => {
    return api.post('/api/v1/enhanced-import/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 获取导入历史
  getImportHistory: (params = {}) => {
    return api.get('/api/v1/enhanced-import/history', { params });
  },

  // 获取任务详情
  getTaskDetail: (taskId) => {
    return api.get(`/api/v1/enhanced-import/task/${taskId}`);
  },

  // 获取统计信息
  getImportStatistics: () => {
    return api.get('/api/v1/enhanced-import/statistics');
  }
};

// 回滚相关API
export const rollbackAPI = {
  // 预览回滚操作
  previewRollback: (taskId) => {
    return api.get(`/api/v1/rollback/preview/${taskId}`);
  },

  // 执行回滚操作
  executeRollback: (taskId, dryRun = false) => {
    return api.post('/api/v1/rollback/execute', {
      task_id: taskId,
      dry_run: dryRun
    });
  },

  // 检查任务是否可以回滚
  canRollback: (taskId) => {
    return api.get(`/api/v1/rollback/can-rollback/${taskId}`);
  },

  // 获取回滚历史记录
  getRollbackHistory: (params = {}) => {
    return api.get('/api/v1/rollback/history', { params });
  }
};

// 通知相关API
export const notificationAPI = {
  // 获取用户通知列表
  getUserNotifications: async (params = {}) => {
    const response = await api.get('/api/v1/notifications/user/', { params });
    return response;
  },

  // 获取未读通知数量
  getUnreadCount: async () => {
    const response = await api.get('/api/v1/notifications/unread/');
    return response;
  },

  // 标记通知为已读
  markAsRead: async (notificationId) => {
    const response = await api.post(`/api/v1/notifications/${notificationId}/read/`);
    return response;
  },

  // 获取所有通知（管理员）
  getAllNotifications: async (params = {}) => {
    const response = await api.get('/api/v1/notifications/', { params });
    return response;
  },

  // 创建通知（管理员）
  createNotification: async (notificationData) => {
    const response = await api.post('/api/v1/notifications/', notificationData);
    return response;
  },

  // 更新通知（管理员）
  updateNotification: async (notificationId, notificationData) => {
    const response = await api.put(`/api/v1/notifications/${notificationId}`, notificationData);
    return response;
  },

  // 删除通知（管理员）
  deleteNotification: async (notificationId) => {
    const response = await api.delete(`/api/v1/notifications/${notificationId}`);
    return response;
  },

  // 批量删除通知（管理员）
  batchDeleteNotifications: async (notificationIds) => {
    const response = await api.post('/api/v1/notifications/batch-delete/', {
      notification_ids: notificationIds
    });
    return response;
  },
};

// 数据统计相关API
export const statisticsAPI = {
  // 获取统计概览
  getStatisticsOverview: async () => {
    const response = await api.get('/api/v1/statistics/overview');
    return response;
  },

  // 获取详细统计
  getDetailedStatistics: async (startDate, endDate) => {
    const response = await api.get('/api/v1/statistics/detail', {
      params: { start_date: startDate, end_date: endDate }
    });
    return response;
  },
};

export default api;